<template>
  <div style="position: relative;left: 0px;top:0px">
    <div :class="curSlideAttributes.tabType === '3' ? 'cardTabTypeClass' :''">
      <div class="globalBackground" :style="globalBackgroundStyle">
        <div v-if="curSlideAttributes.tabType === '1'" :style="tabPaginationStyle">
          <j-tabs
              @click="slideTo"
              style="width: auto"
              v-model="curTabName">
            <j-tab-pane
                v-for="(item, index) in curSlideArr"
                :key="index"
                :label="item.title"
                :name="item.guid">
            </j-tab-pane>
          </j-tabs>
        </div>
        <div v-if="curSlideAttributes.tabType === '2'" :style="buttonPaginationStyle">
          <j-button
              v-for="(item, index) in curSlideArr"
              :key="index"
              :type="curActiveSlideIndex === index ?'line':'normal'"
              :style="{height:curSlideAttributes.buttonHeight + 'px'}"
              @click="slideTo(index)">
            {{ item.title }}
          </j-button>
        </div>
        <el-carousel
            :autoplay="autoplay"
            :interval="interval"
            :type="carouselType"
            :direction="direction"
            :style="carouselContainerWholeStyle"
            :pause-on-hover="false"
            :cardScale="0.68"
            :height="containerHeight"
            ref="carouselEl"
            class="myCarousel"
            indicator-position="none"
            arrow="never"
            @change="changeCarousel"
            v-if="curSlideArr.length"
        >
          <el-carousel-item v-for="(item, index) in curSlideArr" :key="index" :name="index" class="myCarouselItem">
            <div :style="{width:curSlideAttributes.width + 'px' ,height:curSlideAttributes.height + 'px'}"
                 @click="checkSlideResource(item)">
              <j-image
                  fit="scale-down"
                  :src="buildImageUrl( curActiveSlideIndex === index ? item.highlightPicGuid : item.pictureGuid)"
                  :class="curActiveSlideIndex !== index ? 'notActiveSlideClass' : ''"
                  style="height: 100%;width: 100%"
                  @mouseenter="mouseenter"
                  @mouseleave="mouseleave"/>
            </div>
          </el-carousel-item>
        </el-carousel>
        <j-theme-config :theme={radio:{borderColorActive:curSlideAttributes.radioColor,borderColorHover:curSlideAttributes.radioColor}}>
          <j-radio-group
              v-model="curActiveSlideIndex"
              :class="direction === 'horizontal'? 'radio_pagination_horizontal_class' : 'radio_pagination_vertical_class'"
              @change="slideTo"
              v-if="curSlideAttributes.tabType === '0' || curSlideAttributes.tabType === '3'">
            <j-radio
                v-for="(item, index) in curSlideArr"
                :key="index"
                :label="index"
                style="gap: 0px">
              {{}}
            </j-radio>
          </j-radio-group>
        </j-theme-config>
        <div v-if="curSlideAttributes.tabType === '4' && curActiveSlideIndex !== 0"
             :style="slideNavigationButtonLeftContainerStyle"
             @click="slideTo(curActiveSlideIndex - 1)">
          <div
              class="swiper_slide_navigation_button_left_content"
              v-if="!curSlideAttributes.tabPictureGuid "
              :class="curSlideAttributes.tabIconName"/>
          <j-image
              v-if="curSlideAttributes.tabPictureGuid "
              :src="buildImageUrl(curSlideAttributes.tabPictureGuid)"
              fit="scale-down"
              class="swiper_slide_navigation_button_left_content"/>
        </div>
        <div v-if="curSlideAttributes.tabType === '4' && curActiveSlideIndex !== curSlideArr.length - 1"
             :style="slideNavigationButtonRightContainerStyle"
             @click="slideTo(curActiveSlideIndex + 1)">
          <div
              class="swiper_slide_navigation_button_right_content"
              v-if="!curSlideAttributes.tabPictureGuid"
              :class="curSlideAttributes.tabIconName"/>
          <j-image
              v-if="curSlideAttributes.tabPictureGuid"
              :src="buildImageUrl(curSlideAttributes.tabPictureGuid)"
              fit="scale-down"
              class="swiper_slide_navigation_button_right_content"/>
        </div>
        <ResourceBrowseView
            v-if="processSlideGuid !== ''"
            :resArr="processSlideResourceArr"
            :guid="curTopicNavGuid"
            :nodeGuid="processSlideGuid">
        </ResourceBrowseView>
      </div>
    </div>
  </div>
</template>
<script setup>
import {inject, onMounted, reactive, ref} from "vue";
import HttpUtil from "../../../utils/HttpUtil";
import ResourceBrowseView from "@/App.vue";
import {ElCarousel,ElCarouselItem} from "element-plus";
import 'element-plus/dist/index.css'
//================================================【组件通信】============================================================
const context = inject('context')

const props = defineProps(['config'])
const topicNavGuid = props.config.value.topicNavGuid
//================================================【公用相关】============================================================
//carousel组件元素
const carouselEl = ref(null);
//当前幻灯片属性
const curSlideAttributes = reactive({
  width:0,
  height:0,
  switchType:0,
  tabType:0,
  buttonHeight:0,
  tabLocation:0,
  buttonLocation:0,
  tabPictureGuid:'',
  tabIconName:'',
  animationType:0,
  timeIntervalValue:10,
  backgroundType:0,
  transparence:0.5,
  picBackgroundPictureGuid:'',
  picShowType:0,
  colorValue:'',
  radioColor:''
})
//当前幻灯片数组
const curSlideArr = reactive([])
//操作某一张幻灯片绑定的资源数组
const processSlideResourceArr = reactive([]);
//幻灯片跳转
function slideTo(anchorValue) {
  if (curSlideAttributes.tabType === '1'){
    let targetIndex = curSlideArr.findIndex(preFindItem =>{
      return preFindItem.guid === anchorValue
    })
    carouselEl.value.setActiveItem(targetIndex)
  }else{
    carouselEl.value.setActiveItem(anchorValue)
  }
}
//根据oss的guid，构建图片的路径地址
function buildImageUrl(pictureGuid) {
  if (pictureGuid) {
    let baseUrl = HttpUtil.findBaseUrl(context);
    return  baseUrl + "/api/v2/nvwa/topic-navigator/oss/download/" + topicNavGuid + "/" + pictureGuid + ".png";
  }
}
//================================================【组件属性】============================================================
//================================================【普通方法】============================================================
//查询幻灯片属性
function querySlideAttribute() {
  return new Promise((resolve)=>{
    context.getPlugin('http').get('/api/v2/nvwa/topic-navigator/topicNav/prop-data?guid=' + topicNavGuid).then(res => {
      let slideSettingArr = res.data[0].topicNavPropertyList

      curSlideAttributes.height = slideSettingArr[0].slideItemHeight - 0
      curSlideAttributes.width = slideSettingArr[0].slideItemWidth - 0
      containerHeight.value = `${slideSettingArr[0].slideItemHeight - 0}px`
      curSlideAttributes.switchType = slideSettingArr[0].switchType
      curSlideAttributes.tabType = slideSettingArr[0].tabType
      curSlideAttributes.radioColor =  slideSettingArr[0].paginatorColor
      curSlideAttributes.buttonHeight = slideSettingArr[0].buttonHeight
      curSlideAttributes.tabLocation = slideSettingArr[0].tabLocation
      curSlideAttributes.buttonLocation = slideSettingArr[0].buttonLocation
      curSlideAttributes.tabPictureGuid = slideSettingArr[0].pictureGuid
      curSlideAttributes.tabIconName = slideSettingArr[0].value
      curSlideAttributes.animationType = slideSettingArr[0].animationType
      curSlideAttributes.timeIntervalValue = slideSettingArr[0].timeIntervalValue

      curSlideAttributes.backgroundType = slideSettingArr[1].backgroundType
      curSlideAttributes.transparence = (slideSettingArr[1].transparence - 0)/100
      curSlideAttributes.picBackgroundPictureGuid = slideSettingArr[1].pictureGuid
      curSlideAttributes.picShowType = slideSettingArr[1].showType
      curSlideAttributes.colorValue = slideSettingArr[1].colorValue

      resolve()
    })
  })
}

//幻灯片属性设置
//页签分页器样式
const tabPaginationStyle = ref("")
//按钮分页器样式
const buttonPaginationStyle = ref("")
//carousel容器样式
const carouselContainerWholeStyle = ref("")
const autoplay = ref(false)
const interval = ref(0)
const carouselType = ref('')
const direction = ref('horizontal')
const containerHeight = ref('300px')
function slideAttributeSet() {
  //自动操作
  if (curSlideAttributes.switchType === '1') {
    autoplay.value = true
    interval.value = curSlideAttributes.timeIntervalValue * 1000
  }else {
    autoplay.value = false
  }


  //给css传值
  carouselContainerWholeStyle.value =
      `--contentHeight:${curSlideAttributes.height};`

  //页签样式
  //无
  if (curSlideAttributes.tabType === '0') {

    // 展示方向
    if (curSlideAttributes.animationType === "0"){
      direction.value = 'horizontal'
    }
    if (curSlideAttributes.animationType === "1"){
      direction.value = 'vertical'
    }

    carouselContainerWholeStyle.value +=
        `
        width:100%;
        height:100%
        `
  }

  //页签类型
  if (curSlideAttributes.tabType === '1'){
    let curButtonLocationType = ""
    if(curSlideAttributes.tabLocation === '0')
      curButtonLocationType = "left"
    if(curSlideAttributes.tabLocation === '1')
      curButtonLocationType = "center"
    if(curSlideAttributes.tabLocation === '2')
      curButtonLocationType = "end"

    tabPaginationStyle.value =
        `display:flex;
        flex-direction:row;
        justify-content:${curButtonLocationType};
        position: relative;
        z-index: 10;
        background-color: white;`

    carouselContainerWholeStyle.value +=
        `
        width:100%;
        height:calc(100% - 32px)
        `
  }

  //按钮类型
  if (curSlideAttributes.tabType === '2'){
    let curButtonLocationType = ""
    if(curSlideAttributes.buttonLocation === '0')
      curButtonLocationType = "left"
    if(curSlideAttributes.buttonLocation === '1')
      curButtonLocationType = "center"
    if(curSlideAttributes.buttonLocation === '2')
      curButtonLocationType = "end"

    buttonPaginationStyle.value =
        `display:flex;
        flex-direction:row;
        justify-content:${curButtonLocationType};
        gap:8px;
        position: relative;
        z-index: 10;
        background-color: white;
        padding: 8px 8px;`

    carouselContainerWholeStyle.value +=
        `
        width:100%;
        height:calc(100% - ${curSlideAttributes.buttonHeight}px)
        `
  }

  //卡片类型
  if (curSlideAttributes.tabType === '3') {
    carouselType.value = 'card'
    carouselContainerWholeStyle.value +=
        `
        width:100%;
        height:100%
        `
  }

  //自定义右图标
  if (curSlideAttributes.tabType === '4') {
    carouselContainerWholeStyle.value +=
        `
        width:100%;
        height:100%
        `
  }
}
//查询幻灯片填入内容
//tab类型页签的选中值
const curTabName = ref('')
function slideContentQuery() {
  context.getPlugin('http').get('/api/v2/nvwa/topic-navigator/node/getNodeChildren?guid=' + topicNavGuid).then(res => {
    curSlideArr.splice(0, curSlideArr.length, ...res.data)
    if (curSlideArr[0]){
      curTabName.value = curSlideArr[0].guid
    }
  })
}

const rightNavigationPictureWidth = ref(0)
const rightNavigationPictureHeight = ref(0)
function QueryRightNavigationPictureAttribute() {
  return new Promise((resolve)=>{
    if (curSlideAttributes.tabType === '4' && curSlideAttributes.tabPictureGuid){
      // 创建图片对象
      let img = new Image();
      // 设置图片地址
      img.src = buildImageUrl(curSlideAttributes.tabPictureGuid);
      // 判断是否有缓存
      if(img.complete){
        rightNavigationPictureWidth.value = img.width - 0
        rightNavigationPictureHeight.value = img.height - 0

        resolve()
      }else{
        // 加载完成执行
        img.onload = function(){
          rightNavigationPictureWidth.value = img.width - 0
          rightNavigationPictureHeight.value = img.height - 0

          resolve()
        }
      }
    }else
      resolve()
  })
}

function setSlideNavigationButtonContainerStyle() {
  setSlideNavigationButtonLeftContainerStyle()
  setSlideNavigationButtonRightContainerStyle()
}
const slideNavigationButtonLeftContainerStyle = ref('')
function setSlideNavigationButtonLeftContainerStyle(){
  let containerStyle = ''
  if (curSlideAttributes.tabPictureGuid) {
    containerStyle +=
     `width: ${rightNavigationPictureWidth.value}px;
      height: ${rightNavigationPictureHeight.value}px;
      position: relative;
      left: 16px;
      top: -50%;
      z-index: 1;
      transform: translateY(-50%);`
  }else{
    containerStyle +=
     `width: 40px;
      height: 40px;
      position: relative;
      left: 16px;
      top: -50%;
      z-index: 1;
      transform: translateY(-50%);`
  }

  slideNavigationButtonLeftContainerStyle.value = containerStyle
}

const slideNavigationButtonRightContainerStyle = ref('')
function setSlideNavigationButtonRightContainerStyle(){
  let containerStyle = ''
  if (curActiveSlideIndex.value === 0) {
    if (curSlideAttributes.tabPictureGuid) {
      containerStyle +=
          `  width: ${rightNavigationPictureWidth.value}px;
             height: ${rightNavigationPictureHeight.value}px;
             position: relative;
             left: calc(100% - ${rightNavigationPictureWidth.value + 16}px);`
    }else{
      containerStyle +=
          `  width: 40px;
             height: 40px;
             position: relative;
             left: calc(100% - 55px);`
    }
    containerStyle +=
        `  top: -50%;
           z-index: 1;
           transform: translateY(-50%);`
  }else {
    if (curSlideAttributes.tabPictureGuid) {
      containerStyle +=
          `  width: ${rightNavigationPictureWidth.value}px;
             height: ${rightNavigationPictureHeight.value}px;
             position: relative;
             left: calc(100% - ${rightNavigationPictureWidth.value + 16}px);`
    }else{
      containerStyle +=
          `   width: 40px;
              height: 40px;
              position: relative;
              left: calc(100% - 55px);`
    }
    containerStyle +=
        `   top: -50%;
            z-index: 1;
            transform: translateY(-150%);`
  }

  slideNavigationButtonRightContainerStyle.value = containerStyle
}

//当前幻灯片主题导航guid
const curTopicNavGuid = ref("")
//操作某一张幻灯片guid
const processSlideGuid = ref("")
//查看某一张幻灯片资源
function checkSlideResource(slideItem){
  curTopicNavGuid.value = slideItem.navigatorGuid
  processSlideGuid.value = slideItem.guid
  context.getPlugin('http').get("/api/v2/nvwa/topic-navigator/res/node/reslinks?guid=" + processSlideGuid.value).then(res=>{
    processSlideResourceArr.splice(0,processSlideResourceArr.length,...res.data)
    openResourceAppNewWindow(slideItem)
  })
}
//新页面 打开 某一张幻灯片上绑定的资源
function openResourceAppNewWindow(slideItem) {
  //配置信息
  let configData = {
    'resArr': JSON.parse(JSON.stringify(processSlideResourceArr)),
    'topicNavGuid': curTopicNavGuid.value,
    'nodeGuid': processSlideGuid.value,
    'action': 'resourceBrowse',
  }
  // 在挂载点挂载插件
  context.getPlugin('event').emit('open-page', {
    "id": context.getUtils().guid(),
    "appName": 'nvwa-topicnavigator-frontend',
    "prodLine": "@nvwa",
    "title": slideItem.title,
    "openWay": "OPENBLANK",
    "config": configData
  })
}

function mouseenter(){
  if (curSlideAttributes.switchType === '1' && autoplay.value){
    autoplay.value = false
  }
}
function mouseleave(){
  if (curSlideAttributes.switchType === '1' && !autoplay.value){
    autoplay.value = true
  }
}

//全局背景设置
const globalBackgroundStyle = ref('')
function globalBackgroundSet() {
  let backgroundStyle = ''
  if (curSlideAttributes.backgroundType === '0') {
    backgroundStyle = `
    width:100%;
    height:100%;
    `

    backgroundStyle += `background-color:${curSlideAttributes.colorValue};`

  }
  if (curSlideAttributes.backgroundType === '1') {
    backgroundStyle = `
    width:100%;
    height:100%;`

    backgroundStyle += `background-image: url(${buildImageUrl(curSlideAttributes.picBackgroundPictureGuid)});`

    backgroundStyle +=  `--bgColor:${1-curSlideAttributes.transparence};`

    //默认方式
    if (curSlideAttributes.picShowType === '0')
      backgroundStyle += `background-repeat:no-repeat;background-position:left top;`
    //居中方式
    if (curSlideAttributes.picShowType === '1')
      backgroundStyle += `background-repeat:no-repeat;background-position:center center;`
    //拉伸方式
    if (curSlideAttributes.picShowType === '2')
      backgroundStyle += `background-repeat:no-repeat;background-size:cover;`
    //平铺方式
    if (curSlideAttributes.picShowType === '3')
      backgroundStyle += `background-repeat:repeat;`

  }
  globalBackgroundStyle.value = backgroundStyle
}

const curActiveSlideIndex = ref(0);
/**
 * 切换轮播时事件
 * @param currIdx 当前激活的索引
 * @param oldIdx  旧激活索引
 */
function changeCarousel(currIdx,oldIdx){
  curActiveSlideIndex.value = currIdx
  curTabName.value = curSlideArr[currIdx].guid

  //当激活页签改变，需要动态调整右图标样式
  setSlideNavigationButtonContainerStyle()
}
//================================================【生命周期】============================================================
//mounted 初始化页面完成进行操作
onMounted(()=>{

  querySlideAttribute().then(() => {
    slideAttributeSet()
    slideContentQuery()
    QueryRightNavigationPictureAttribute().then(
        setSlideNavigationButtonContainerStyle()
    )
    globalBackgroundSet()
  })
})

</script>

<style scoped>
.cardTabTypeClass{
  height: calc(100% - 32px) !important;
  width: calc(100% - 32px) !important;
  position: absolute;
  margin: 16px;
}
.globalBackground{
  width: 100%;
  height: 100%;
  position: absolute;
  left: 0;
  top: 0;
  overflow: hidden;
}
.globalBackground::after {
  content: "";
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(255, 255, 255, var(--bgColor));
}
.notActiveSlideClass{
  opacity: 0.48;
}
:deep(.myCarousel >.el-carousel__container>.el-carousel__item>.el-carousel__mask){
  display: none;
}
.swiper_slide_navigation_button_left_content{
  width: 100% !important;
  height: 100% !important;
  transform: rotateY(180deg);
  display: flex;
  flex-direction: row;
  justify-content: center;
  align-items: center;
  font-size: 40px;
}
.swiper_slide_navigation_button_right_content{
  width: 100% !important;
  height: 100% !important;
  display: flex;
  flex-direction: row;
  justify-content: center;
  align-items: center;
  font-size: 40px;
}
.radio_pagination_horizontal_class{
  position: absolute;
  left: 50%;
  bottom: 2%;
  transform: translate(-50%);
  z-index: 1;
  background: #ffffff29;
  border-radius: 16px;
  backdrop-filter: blur(4px);
  padding: 0 8px;
}
.radio_pagination_vertical_class{
    position: absolute;
    left: 95%;
    bottom: 50%;
    Transform: translateY(50%) rotate(-90deg);
    z-index: 1;
    background: #ffffff29;
    border-radius: 16px;
    -webkit-backdrop-filter: blur(4px);
    backdrop-filter: blur(4px);
    padding: 0 8px;
}

.myCarouselItem{
  height: var(--contentHeight)px;
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: center;
}
:deep(.myCarousel > .el-carousel__container){
  position: relative;
  top: 50%;
  transform: translateY(-50%);
  z-index: 1
}
</style>
